<template>
  <div class="app-container">
    <!--工具栏-->

    <div style="margin-top: 20px">
      <el-form
        size="small"
        label-width="100px"
        v-formkey="{ query: crud.toQuery }"
      >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务日期">
              <div class="flex flex-row">
                <el-date-picker
                  v-model="query.startTime"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
                <el-date-picker
                  v-model="query.endTime"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="结束日期"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="编码">
              <el-input v-model="query.code" placeholder="输入编码进行搜索" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="下游单据编码">
              <el-input
                v-model="query.downOrderCode"
                placeholder="输入下游单据编码进行搜索"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品名称">
              <el-input
                v-model="query.goodsName"
                placeholder="输入商品名称进行搜索"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品">
              <table-select
                :tableColumns="[
                  { prop: 'goodsCode', label: '商品编码', width: '100' },
                  { prop: 'goodsName', label: '商品名称', width: '280' }
                ]"
                labelKey="goodsName"
                valueKey="goodsId"
                :value.sync="query.goodsIds"
                placeholder="请选择商品"
                url="/api/dropDown/basGoodsListForAdd"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户名称">
              <table-select
                :tableColumns="[
                  { prop: 'code', label: '单位编码', width: '100' },
                  { prop: 'name', label: '往来单位名称', width: '280' }
                ]"
                :value.sync="query.customerIds"
                placeholder="请选择往来单位"
                url="/api/dropDown/basCustomerList"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态">
              <el-select
                multiple
                v-model="orderStatus"
                class="edit-input"
                placeholder="请选择单据状态"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_order_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户区域" prop="customerAreaId">
              <treeselect
                v-model="query.customerAreaId"
                :options="areaList"
                placeholder="选择客户区域"
                style="width: 100%"
                :normalizer="normalizer"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="仓库">
              <zSelect
                :value.sync="query.warehouseId"
                url="api/dropDown/basWarehouseList"
              />
            </el-form-item>
          </el-col>
          <!--          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
          <!--            <el-form-item label="来源类型">-->
          <!--              <el-select v-model="query.sourceType" style="width:  100%"  class="edit-input" placeholder="请选择来源类型" >-->
          <!--                <el-option-->
          <!--                  v-for="(item,index) in dict.t_mobile_order_source_type"-->
          <!--                  :key="index"-->
          <!--                  v-if="item.seq>0"-->
          <!--                  :label="item.label"-->
          <!--                  :value="item.value"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="备注">
              <el-input v-model="query.remark" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="添加人">
              <zSelect
                :value.sync="query.createUserId"
                :showName="query.userName"
                url="api/dropDown/sysUserList"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="打印状态">
              <el-select
                clearable
                v-model="query.isPrint"
                style="width: 100%;"
                class="edit-input"
                placeholder="请选择打印状态"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否发货">
              <el-select
                clearable
                v-model="query.isDelivery"
                style="width: 100%;"
                class="edit-input"
                placeholder="请选择发货状态"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="二级代理">
              <zSelect
                :value.sync="query.sCustomerId"
                url="api/dropDown/basCustomerList"
                :params="{ type: 3 }"
                style="width:  100%;"
              />
              <!--                <el-input v-model="query.sCustomerName" style="width: 100%;"/>-->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据类型">
              <el-select
                v-model="query.type"
                style="width:  100%"
                class="edit-input"
                placeholder="请选择单据类型"
              >
                <el-option
                  v-for="(item, index) in dict.t_sales_order_type"
                  :key="index"
                  v-if="item.seq > 0"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="验收状态">
              <el-select
                v-model="query.isAccept"
                class="edit-input"
                placeholder="请选择验收状态"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="支付状态">
              <el-select
                v-model="query.payStatus"
                class="edit-input"
                placeholder="请选择支付状态"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.pay_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否预订">
              <el-select
                v-model="query.isAdvance"
                class="edit-input"
                placeholder="是否预订"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否挂账">
              <el-select
                v-model="query.isOnAccount"
                class="edit-input"
                placeholder="是否挂账"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="6"
            align="center"
            style="margin-bottom: 10px;margin-top: 5px"
          >
            <!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              @click="crud.toQuery()"
              >搜索</el-button
            >
            <el-button
              class="filter-item"
              plain
              size="mini"
              type="primary"
              @click="resetQuery"
              >重置</el-button
            >
            <!--            </el-col>-->
          </el-col>
        </el-row>
      </el-form>
    </div>
    <crudOperation :permission="permission" v-if="!isExceed">
      <el-button
        slot="left"
        v-permission="permission.add"
        class="filter-item"
        size="mini"
        type="primary"
        @click="toDetail('salesOrderDetail')"
      >
        新增
      </el-button>
      <el-button
        slot="left"
        v-permission="permission.edit"
        class="filter-item"
        size="mini"
        type="success"
        :disabled="crud.selections.length !== 1"
        @click="toEdit(crud.selections[0])"
      >
        修改
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        @click="crud.saleToAccept()"
        :disabled="crud.selections.length < 1"
        v-permission="permission.accept"
      >
        验收
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        @click="toUnAccept()"
        :disabled="crud.selections.length < 1"
        v-permission="permission.accept"
      >
        取消验收
      </el-button>
      <!--<el-button-->
      <!--slot="right"-->
      <!--class="filter-item"-->
      <!--size="mini"-->
      <!--@click="crud.toSplit()"-->
      <!--:disabled="crud.selections.length < 1"-->
      <!--v-permission="permission.split"-->
      <!--&gt;-->
      <!--单据拆分-->
      <!--</el-button>-->
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        @click="showHistory()"
        :disabled="crud.selections.length < 1"
      >
        单据记录
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        @click="handleCopyToReturn()"
        :disabled="crud.selections.length < 1"
        v-permission="permission.copyToReturn"
      >
        复制为退货
      </el-button>
      <el-button
        slot="left"
        class="filter-item"
        size="mini"
        type="success"
        @click="bomStockCheck"
        :disabled="crud.selections.length === 1"
        v-permission="permission.checkBomStock"
      >
        检查BOM库存
      </el-button>
      <!--        <el-button-->
      <!--          slot="right"-->
      <!--          class="filter-item"-->
      <!--          size="mini"-->
      <!--          type="warning"-->
      <!--          icon="el-icon-notebook-2"-->
      <!--          :disabled="crud.selections.length < 1"-->
      <!--          :loading="crud.printLoading"-->
      <!--          @click="crud.doPrint('printTemplate-1e3c24b3-7b3b-403b-bb05-bb12092a8516')"-->
      <!--          v-permission="permission.print"-->
      <!--        >-->
      <!--          打印-->
      <!--        </el-button>-->
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-notebook-2"
        :disabled="crud.selections.length !== 1"
        @click="volume()"
      >
        批量折扣
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="warning"
        @click="acceptInfo"
      >
        同步拣货信息
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="warning"
        @click="printIsSave"
        >打印</el-button
      >
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.preView1"
        >打印预览</el-button
      >
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="warning"
        :disabled="crud.selections.length !== 1"
        @click="feiEPrint()"
        >飞鹅小票打印</el-button
      >
      <el-button
        slot="right"
        size="mini"
        type="info"
        class="filter-item"
        :disabled="crud.selections.length < 1"
        @click="onlinePayQuery()"
      >
        线上支付查询
      </el-button>
      <el-button
        slot="right"
        size="mini"
        type="info"
        class="filter-item"
        :disabled="crud.selections.length !== 1"
        @click="
          order = crud.selections[0];
          superCancelShow = true;
        "
        v-permission="permission.superCancel"
      >
        一键核销
      </el-button>
      <el-button
        slot="right"
        size="mini"
        type="info"
        class="filter-item"
        @click="unCancel(crud.selections[0].id)"
        :disabled="crud.selections.length !== 1"
        v-permission="permission.superUnCancel"
      >
        一键反核销
      </el-button>
      <el-button
        slot="right"
        size="mini"
        type="info"
        class="filter-item"
        @click="settlement"
        v-permission="permission.settlement"
        :disabled="crud.selections.length !== 1"
      >
        结算
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="success"
        @click="showAccounting = true"
        :disabled="crud.selections.length !== 1"
        v-permission="permission.onAccount"
      >
        挂账
      </el-button>

      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.toSuperPass"
        v-permission="permission.superPass"
        :disabled="crud.selections.length === 0"
      >
        超级审核
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="success"
        @click="dialogCheckMaterialWareHouse = true"
      >
        检查原料
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="success"
        @click="goRefund()"
        :disabled="crud.selections.length !== 1"
      >
        同意退款
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="success"
        @click="dialogRefund = true"
        :disabled="crud.selections.length !== 1"
      >
        拒绝退款
      </el-button>
    </crudOperation>
    <j-dialog
      title="检查bom"
      :visible.sync="lackBomShow"
      isMask
      style="width: 80vw;"
    >
      <goods-demand
        :warehouse-id="checkMaterialWareHouse.id"
        @close="lackBomShow = false"
        :sales-order-ids="selectIds"
      />
    </j-dialog>
    <!--检查库存仓库仓库-->
    <j-dialog
      is-mask
      title="检查仓库"
      style="width: 500px"
      :visible.sync="dialogCheckMaterialWareHouse"
    >
      <el-form ref="form" label-width="80px" size="small">
        <el-form-item label="检查仓库">
          <zSelect
            :value.sync="checkMaterialWareHouse.id"
            @change="checkMaterialWareHouse = $event"
            :showName="checkMaterialWareHouse.name"
            url="api/dropDown/basWarehouseList"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex flex-reverse">
        <el-button @click="dialogCheckMaterialWareHouse = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="showLackBom()">确 定</el-button>
      </div>
    </j-dialog>

    <j-dialog
      is-mask
      title="拒绝退款"
      style="width: 500px"
      :visible.sync="dialogRefund"
    >
      <el-form ref="form" label-width="80px" size="small">
        <el-form-item label="退款原因">
          <el-input
            v-model="refuseRefundReason"
            placeholder="输入退款原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex flex-reverse">
        <el-button @click="dialogRefund = false">取 消</el-button>
        <el-button type="primary" @click="refuseRefund()">确 定</el-button>
      </div>
    </j-dialog>

    <el-dialog
      title="打印预览"
      destroy-on-close
      v-dialogDrag
      close-on-press-escape
      :visible.sync="showPdf"
      append-to-body
      width="50vw"
    >
      <j-pdf :src="pdfSrc"></j-pdf>
    </el-dialog>

    <el-dialog
      title="挂账"
      destroy-on-close
      v-dialogDrag
      close-on-press-escape
      :visible.sync="showAccounting"
      append-to-body
      width="30vw"
    >
      <zSelect
        :value.sync="customerAccounting"
        url="api/dropDown/basCustomerList"
        style="width:  100%;"
      />
      <el-button style="margin:20px 0 0 90%" @click="saveAccounting">
        确认
      </el-button>
    </el-dialog>

    <div class="body-container">
      <!--表格渲染-->
      <!--      @header-click="handleHeaderCLick"-->
      <!--      @sort-change="sortTab"-->
      <el-table
        ref="table"
        border
        @header-dragend="changeColWidth"
        highlight-current-row="highlight-current-row"
        :height="tableHeight"
        show-summary
        @cell-dblclick="row => crud.toEdit(row)"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        v-draghead="manyTableOption"
        @sort-change="sortTab"
        :summary-method="crud.sumRow"
        @row-click="row => changeDetailQuery(row)"
        :row-style="crud.rowClass"
        :row-class-name="crud.tableRowClassName"
        @selection-change="crud.selectionChangeHandler"
        @row-dblclick="row => setQuery(row.id)"
      >
        <el-table-column
          :render-header="crud.renderHeader"
          fixed
          type="selection"
          width="60"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          fixed
          type="index"
          width="60"
          label="序号"
        />
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp="item.prop"
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
          :fixed="item.fixed"
          :sortable="item.sortable ? 'custom' : false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template>
              <span
                :class="{ blue: scope.row['orderStatus'] === 'INVALID' }"
                v-if="item.type == 1"
                style="margin-left: 0px"
              >
                <span
                  :class="{
                    red: scope.row[`type`] === 2,
                    blue: item.orderStatus === 'INVALID'
                  }"
                >
                  {{ scope.row[`${item.prop}`] }}
                </span>
              </span>
              <span
                :class="{ blue: scope.row['orderStatus'] === 'INVALID' }"
                v-else-if="item.type == 2"
                style="margin-left: 0px"
                >{{ parseTime(scope.row[`${item.prop}`]) }}</span
              >
              <span
                :class="{ blue: scope.row['orderStatus'] === 'INVALID' }"
                v-else-if="item.type == 3"
                style="margin-left: 0px"
              >
                <span :class="{ red: scope.row[`type`] === 2 }">
                  {{
                    getDict(
                      `this.dict.label.${item.dictionary}["${
                        scope.row[item.prop]
                      }"]`
                    )
                  }}
                </span>
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination />
      <j-bill-detail
        url="/api/salesOrder/detail"
        type="get"
        :headerQuery="headerQuery"
        :params="detailParams"
      ></j-bill-detail>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig
          groupId="salesOrder"
          v-if="crud.printConfig.pringDialog"
          @getPrintId="crud.toPrint"
          :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <el-dialog title="核销" :visible.sync="superCancelShow" width="30%">
        <div>
          <el-form
            label-width="80px"
            ref="cancelForm"
            :model="cancel"
            :rules="cancelRules"
          >
            <el-form-item label="银行" prop="bankId">
              <zSelect
                :value.sync="cancel.bankId"
                url="api/dropDown/basBankList"
              />
            </el-form-item>
            <el-form-item label="收款金额" prop="receiptAmount">
              <el-input type="number" v-model="cancel.receiptAmount"></el-input>
            </el-form-item>
            <el-form-item label="尾差金额" prop="tailAmount">
              <el-input type="number" v-model="cancel.tailAmount"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="cancel.receiptRemark"
              ></el-input>
            </el-form-item>
            <el-form-item label="已核销金额">
              <el-input disabled v-model="order.cancelAmount"></el-input>
            </el-form-item>
            <el-form-item label="未核销金额">
              <el-input disabled v-model="order.unCancelAmount"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex flex-reverse">
          <el-button @click="saveCancel">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="结算" :visible.sync="settlementShow" width="30%">
        <div>
          <el-form
            label-width="80px"
            ref="cancelForm"
            :model="cancel"
            :rules="cancelRules"
          >
            <el-form-item label="已核销金额">
              <el-input
                disabled
                v-model="settlementData.order.cancelAmount"
              ></el-input>
            </el-form-item>
            <el-form-item label="未核销金额">
              <el-input
                disabled
                v-model="settlementData.order.unCancelAmount"
              ></el-input>
            </el-form-item>
            <el-form-item label="选择收款单">
              <table-select
                :tableColumns="[
                  { prop: 'busDate', label: '业务日期', width: '100' },
                  { prop: 'receiptCode', label: '收款单号', width: '150' },
                  { prop: 'taxAmount', label: '收款金额' },
                  { prop: 'cancelAmount', label: '已核销金额' },
                  { prop: 'unCancelAmount', label: '未核销金额' }
                ]"
                labelKey="receiptCode"
                valueKey="receiptId"
                width="800"
                @change="deductionAmount"
                :value.sync="settlementForm.receiptIds"
                placeholder="请选择收款单"
                :params="{
                  customerId: settlementData.customerId
                }"
                url="api/salesOrder/settlement/draw"
              />
            </el-form-item>
            <el-form-item label="客户抵扣券" prop="tailAmount">
              <el-input
                type="number"
                disabled
                v-model="settlementData.customerDeductionAmount"
              ></el-input>
            </el-form-item>
            <el-form-item label="尾差金额" prop="tailAmount">
              <el-input
                type="number"
                @change="deductionAmount"
                v-model="settlementForm.tailAmount"
              ></el-input>
            </el-form-item>
            <el-form-item label="抵扣金额">
              <el-input
                type="number"
                @change="setDeductionAmount"
                v-model="settlementForm.deductionAmount"
              ></el-input>
            </el-form-item>
            <el-form-item label="扣款金额">
              <el-input
                type="number"
                disabled
                @change="setDeductionAmount"
                v-model="settlementForm.curCancelAmount"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex flex-reverse">
          <el-button @click="saveSettlement">确定</el-button>
        </div>
      </el-dialog>
      <!--分页组件-->
      <!--表单组件-->
      <el-dialog
        :before-close="cancelCU"
        :close-on-click-modal="false"
        title="退货"
        :visible.sync="isCopyToReturn"
        append-to-body
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
          size="small"
        >
          <el-form-item label="仓库">
            <zSelect
              :value.sync="form.warehouseId"
              :showName="form.warehouseName"
              url="api/dropDown/basWarehouseList"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancelCU">取消</el-button>
          <el-button
            :loading="crud.cu === 2"
            type="primary"
            @click="crud.toCopyToReturn(form)"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <vue-context-menu
        :contextMenuData="contextMenuData"
        @tableConfig="tableConfig"
        @deletedata="deletedata"
      ></vue-context-menu>
    </div>
    <!--销售记录弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      title="销售记录"
      :visible.sync="showHistoryDialog"
      append-to-body
      width="80vw"
    >
      <history
        :data="current"
        :showAddBatchDialog.sync="showHistoryDialog"
        @change="afterChangeGoods"
      ></history>
    </el-dialog>
    <right-click-menu
      @tableConfig="tableConfig"
      :options.sync="rightClickMenuConfig"
    ></right-click-menu>
    <el-dialog title="表格配置" :visible.sync="tableConfigShow" width="60%">
      <j-table-column-config
        :columns.sync="currentHeader"
        @tabSave="saveHead"
      />
    </el-dialog>
    <!--    批量折扣-->
    <el-dialog title="批量折扣" :visible.sync="isVolume" width="25%">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="按品牌折扣" name="1">
          <el-table border :data="goodsBrandDiscountList" style="width: 100%">
            <el-table-column prop="goodsBrandName" label="品牌名称">
            </el-table-column>
            <el-table-column prop="discountRate" label="折扣率">
              <template slot-scope="scope">
                <el-input-number
                  :step="0.1"
                  :min="0"
                  :max="100"
                  v-model="scope.row.discountRate"
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按分类折扣" name="2">
          <el-table border :data="goodsTypeDiscountList" style="width: 100%">
            <el-table-column prop="goodsTypeName" label="商品分类">
            </el-table-column>
            <el-table-column prop="discountRate" label="折扣率" width="180">
              <template slot-scope="scope">
                <el-input-number
                  :step="0.1"
                  :min="0"
                  :max="100"
                  v-model="scope.row.discountRate"
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="整单折扣" name="3">
          <el-table border :data="goodsDiscountList" style="width: 100%">
            <el-table-column prop="discountRate" label="整单折扣">
              <template slot-scope="scope">
                <el-input-number
                  :step="0.1"
                  :min="0"
                  :max="100"
                  v-model="scope.row.discountRate"
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelCUDis">取消</el-button>
        <el-button
          :loading="crud.cu === 2"
          type="primary"
          @click="handleDisCl()"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="搜索"
      :before-close="handleClose"
      destroy-on-close
      v-dialogDrag
      close-on-press-escape
      width="80%"
      :visible.sync="!crud.props.searchToggle"
    >
      <el-form size="small" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务日期">
              <div class="flex flex-row">
                <el-date-picker
                  v-model="query.startTime"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
                <el-date-picker
                  v-model="query.endTime"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="结束日期"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="装车日期">
              <div class="flex flex-row">
                <el-date-picker
                  v-model="query.loadStartDate"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
                <el-date-picker
                  v-model="query.loadEndDate"
                  align="right"
                  unlink-panels
                  class="fl1"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="结束日期"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="编码">
              <el-input v-model="query.code" placeholder="输入编码进行搜索" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="总店">
              <zSelect
                :value.sync="query.pCustomerId"
                :showName="query.pCustomerName"
                url="api/dropDown/basCustomerList"
                :params="{ customerAttr: 1 }"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户区域" prop="customerAreaId">
              <treeselect
                v-model="query.customerAreaId"
                :options="areaList"
                placeholder="选择客户区域"
                style="width: 100%"
                :normalizer="normalizer"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户分类" prop="customerTypeId">
              <treeselect
                v-model="customerTypeIds"
                :options="typeList"
                placeholder="客户分类"
                style="width: 100%"
                :normalizer="normalizer"
                multiple
                @input="val => getNoStr(val, 'typeList', 'customerTypeIds')"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户名称">
              <zSelect
                :value.sync="query.customerId"
                :showName="query.customerName"
                url="api/dropDown/basCustomerList"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务员">
              <zSelect
                :value.sync="query.userId"
                :showName="query.userName"
                url="api/dropDown/sysUserList"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="销售部门">
              <treeselect
                v-model="query.deptId"
                :options="depts"
                placeholder="选择部门"
                style="width:  100%"
                :normalizer="normalizer"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="打印状态">
              <el-select
                v-model="query.isPrint"
                style="width: 100%;"
                class="edit-input"
                placeholder="请选择打印状态"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据状态">
              <el-select
                multiple
                v-model="orderStatus"
                class="edit-input"
                placeholder="请选择单据状态"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_order_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
          <!--            <el-form-item label="单据状态">-->
          <!--              <el-select multiple v-model="orderStatus" class="edit-input" placeholder="请选择单据状态" clearable style="width: 100%;">-->
          <!--                <el-option-->
          <!--                  v-for="(item,index) in dict.common_order_status"-->
          <!--                  :key="index"-->
          <!--                  :label="item.label"-->
          <!--                  :value="item.value"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="核销状态">
              <el-select
                v-model="query.cancelStatus"
                class="edit-input"
                placeholder="请选择核销状态"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_cancel_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否往来">
              <el-select
                v-model="query.isContact"
                class="edit-input"
                placeholder="请选择是否往来"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.t_bas_customer_is_contact"
                  :key="index"
                  v-if="item.seq > 0"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据类型">
              <el-select
                v-model="query.type"
                style="width:  100%"
                class="edit-input"
                placeholder="请选择单据类型"
              >
                <el-option
                  v-for="(item, index) in dict.t_sales_order_type"
                  :key="index"
                  v-if="item.seq > 0"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="来源类型">
              <el-select
                v-model="query.sourceType"
                style="width:  100%"
                class="edit-input"
                placeholder="请选择来源类型"
              >
                <el-option
                  v-for="(item, index) in dict.t_sales_order_source_type"
                  :key="index"
                  v-if="item.seq > 0"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
          <!--            <el-form-item label="来源类型">-->
          <!--              <el-select v-model="query.sourceType" style="width:  100%"  class="edit-input" placeholder="请选择来源类型" >-->
          <!--                <el-option-->
          <!--                  v-for="(item,index) in dict.t_mobile_order_source_type"-->
          <!--                  :key="index"-->
          <!--                  v-if="item.seq>0"-->
          <!--                  :label="item.label"-->
          <!--                  :value="item.value"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="来源单据编码">
              <el-input v-model="query.sourceCode" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="备注">
              <el-input v-model="query.remark" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据说明">
              <el-input v-model="query.orderRemark" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="配送单号">
              <el-input v-model="query.loadCode" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="二级代理">
              <zSelect
                :value.sync="query.sCustomerId"
                url="api/dropDown/basCustomerList"
                :params="{ type: 3 }"
                style="width:  100%;"
              />
              <!--                <el-input v-model="query.sCustomerName" style="width: 100%;"/>-->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户单号">
              <el-input
                v-model="query.customerOrderCode"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="添加人">
              <zSelect
                :value.sync="query.createUserId"
                :showName="query.userName"
                url="api/dropDown/sysUserList"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="审核人">
              <zSelect
                :value.sync="query.auditUserId"
                :showName="query.auditUserName"
                url="api/dropDown/sysUserList"
                style="width:  100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否超账期">
              <el-select
                v-model="query.isExceed"
                class="edit-input"
                placeholder="是否超账期"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" style="text-align: center">
          <!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            @click="toQuery"
            >搜索</el-button
          >
          <el-button
            class="filter-item"
            plain
            size="mini"
            type="primary"
            @click="resetQuery"
            >重置</el-button
          >
          <!--            </el-col>-->
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import crudSalesOrder, {
  deptJuniorUserList,
  refundOrder
} from "@/api/erp/salesOrder";
import CRUD, { crud, form, header, presenter } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { getDepts } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import { getCustomerTypeTree } from "@/api/erp/basCustomerType";
import { getAreaTree } from "@/api/erp/basCustomerArea";
import history from "@/views/erp/salesOrder/history";
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import JtgTree from "@/components/Tree/JtgTreePlus";
import { manyTableMixin } from "../../../mixins/manyTableMixin";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import { publicListKey } from "@/utils/key";
import jBillDetail from "@/components/jBillDetail/jBillDetail";
import {
  batchDiscount,
  getBatchDiscountInfo,
  getSalesOrderPreviousNextPageIdList,
  salesOrdersyncSalesOrderAcceptInfo,
  superCancel,
  superUnCancel,
  feiEPrint,
  settlementDraw,
  settlementSave,
  onlinePayQuery,
  saveAccounting,
  checkBomStock
} from "../../../api/erp/salesOrder";
import goodsDemand from "@/components/goodsDemand/index.vue";
import jDialog from "@/components/jDialog/jDialog.vue";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "销售单",
  url: "api/salesOrder",
  name: "salesOrder",
  sort: "id,desc",
  crudMethod: { ...crudSalesOrder },
  query: { orderStatus: "SAVE", isPrint: null },
  optShow: {
    add: false,
    edit: false,
    del: true,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false,
    pass: true,
    reject: true,
    invalid: true,
    recover: true,
    downloadDetail: true,
    exportDetail: true,
    print: false,
    printDetail: false,
    accept: false,
    unAccept: false
  },
  props: {
    //在这里配置要显示的字段
    tableColumns: [
      // 'id', //id".
      "code", //编码".
      "name", //名称".
      "isDelivery",//是否发货 0未发货
      "type", //销售单类型(1:销售订单 2:退货单,".
      "saleType", //销售类型(1:正常销售 2:代配送 3:赠品出库 4:租转售,".
      "busDate", //业务日期.
      "sourceType", //sourceType.
      "sourceId", //来源单据id".
      "sourceCode", //来源单据号".
      "serialNumber", //流水号".
      "customerOrderCode", //客户单号".
      // 'customerId', //客户id".
      // 'customerCode', //客户编码".
      "customerName", //客户名称".
      "isContact", //是否往来(0:客户 1:供应商 2:客户+供应商,".
      // 'deptId', //部门id".
      // 'deptCode', //部门编码".
      "deptName", //部门名称".
      // 'userId', //人员id".
      // 'userCode', //人员编码".
      "userName", //人员名称".
      // 'warehouseId', //仓库id".
      // 'warehouseCode', //仓库编码".
      "warehouseName", //仓库名称".
      "count", //条数".
      "boxCount", //箱数".
      "taxAmount", //含税金额".
      "noTaxAmount", //未税金额".
      "tax", //税额".
      "discountAmount", //折扣金额".
      "acceptBoxCount", //验收箱数".
      "acceptTaxAmount", //验收含税金额".
      "acceptNoTaxAmount", //验收未税金额".
      "acceptTax", //验收税额".
      "cancelAmount", //已核销金额".
      "unCancelAmount", //未核销金额".
      "receiveDate", //应收日期">
      // 'carId', //装车车辆id".
      // 'carCode', //装车车辆编码".
      "carName", //装车车辆名称".
      // 'loadId', //装车单id".
      "loadCode", //装车单号".
      "loadTime", //装车时间">
      // 'driverUserId', //司机id".
      // 'driverUserCode', //司机编码".
      "driverUserName", //司机名称".
      // 'followUserId', //跟车id".
      // 'followUserIds', //跟车ids".
      // 'followUserCode', //跟车编码".
      "followUserName", //跟车名称".
      "isPrint", //打印状态(0:否 1:是,".
      "printCount", //打印次数".
      // 'customerAreaId', //客户区域id".
      // 'customerAreaCode', //客户区域编码".
      "customerAreaName", //客户区域名称".
      // 'customerTypeId', //客户分类id".
      // 'customerTypeCode', //客户分类编码".
      "customerTypeName", //客户分类名称".
      // 'pCustomerId', //所属总店id".
      // 'pCustomerCode', //所属总店编码".
      "pCustomerName", //所属总店名称".
      // 'mCustomerId', //所属商场id".
      // 'mCustomerCode', //所属商场编码".
      "mCustomerName", //所属商场名称".
      // 'sCustomerId', //二级代理id".
      // 'sCustomerCode', //二级代理编码".
      "sCustomerName", //二级代理名称".
      "seq", //排序".
      "orderStatus", //orderStatus
      "acceptStatus", //验收状态(0:否 1:是,".
      "cancelStatus", //核销状态(0:未核销 1:部分核销 2:已核销,".
      "remark", //备注".
      "orderRemark" //单据说明".
      // 'createUserId', //添加人id".
      // 'createUserCode', //添加人编码".
      // 'createUserName', //添加人名称".
      // 'createTime', //添加时间">
      // 'updateUserId', //修改人id".
      // 'updateUserCode', //修改人编码".
      // 'updateUserName', //修改人名称".
      // 'updateTime', //修改时间">
      // 'closeUserId', //关闭人id".
      // 'closeUserCode', //关闭人编码".
      // 'closeUserName', //关闭人名称".
      // 'closeTime', //关闭时间">
    ]
  },
  queryOnPresenterCreated: false
});
const defaultForm = {
  id: null,
  code: null,
  downOrderCode: null,
  name: null,
  type: null,
  saleType: 1,
  busDate: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  serialNumber: null,
  customerOrderCode: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  isContact: null,
  isDelivery:0,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  count: null,
  boxCount: null,
  taxAmount: null,
  noTaxAmount: null,
  tax: null,
  discountAmount: null,
  acceptBoxCount: null,
  acceptTaxAmount: null,
  acceptNoTaxAmount: null,
  acceptTax: null,
  cancelAmount: null,
  unCancelAmount: null,
  receiveDate: null,
  carId: null,
  carCode: null,
  carName: null,
  loadId: null,
  loadCode: null,
  loadTime: null,
  driverUserId: null,
  driverUserCode: null,
  driverUserName: null,
  followUserId: null,
  followUserIds: null,
  followUserCode: null,
  followUserName: null,
  printStatus: null,
  printCount: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  pCustomerId: null,
  pCustomerCode: null,
  pCustomerName: null,
  mCustomerId: null,
  mCustomerCode: null,
  mCustomerName: null,
  sCustomerId: null,
  sCustomerCode: null,
  sCustomerName: null,
  seq: null,
  orderStatus: null,
  acceptStatus: null,
  cancelStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null,
  auditUserId: null,
  auditUserName: null,
  exchangeWarehouseId: null,
  isDelivery:null
};
export default {
  name: "salesOrder",
  components: {
    jDialog,
    goodsDemand,
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Treeselect,
    history,
    jPrintConfig,
    JtgTree,
    jTableColumnConfig,
    jBillDetail
  },
  mixins: [
    presenter(defaultCrud),
    header(),
    form(defaultForm),
    crud(),
    manyTableMixin,
    publicListKey
  ],
  dicts: [
    "t_bas_customer_is_contact",
    "common_cancel_status",
    "common_order_status",
    "common_yes_or_no",
    "t_sales_order_type",
    "t_sales_order_source_type",
    "t_sales_order_sale_type",
    "t_mobile_order_source_type",
    "t_sales_order_save_order_status_is_allow_print",
    "pay_status"
  ],
  data() {
    return {
      form: JSON.parse(JSON.stringify(defaultForm)),
      dialogChangeWarehouse: false,
      cancel: {
        bankId: null,
        receiptAmount: null,
        tailAmount: null,
        receiptRemark: null
      },
      lackBomShow: false,
      checkMaterialWareHouse: { id: 0, name: "" },
      dialogCheckMaterialWareHouse: false,
      dialogRefund: false,
      refuseRefundReason: "",
      customerAccounting: null,
      settlementForm: {
        deductionAmount: 0,
        receiptIds: "",
        curCancelAmount: 0,
        tailAmount: 0
      },

      settlementData: {
        customerDeductionAmount: 0,
        customerId: "",
        order: {}
      },
      cancelRules: {
        bankId: [{ required: true, message: "请选择银行", trigger: "blur" }],
        receiptAmount: [
          { required: true, message: "请输入金额", trigger: "blur" }
        ]
      },
      order: {},
      settlementShow: false,
      goodsBrandDiscountList: [],
      goodsDiscountList: [],
      goodsTypeDiscountList: [],
      customerTypeList: [],
      customerTypeIds: [],
      superCancelShow: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      dataExtent: [],
      isExceed: false,
      showHistoryDialog: false,
      sales_order_type_list: [
        {
          label: "销售订单",
          value: "SALE"
        },
        {
          label: "销售退货单",
          value: "SALE_RETURN"
        }
      ],
      isVolume: false,
      permission: {
        add: ["admin", "salesOrder:add"],
        edit: ["admin", "salesOrder:edit"],
        del: ["admin", "salesOrder:del"],
        import: ["admin", "salesOrder:import"],
        export: ["admin", "salesOrder:export"],
        copy: ["admin", "salesOrder:copy"],
        upload: ["admin", "salesOrder:upload"],
        download: ["admin", "salesOrder:download"],
        // downloadDetail: ['admin', 'salesOrder:downloadDetail'],
        pass: ["admin", "salesOrder:pass"],
        reject: ["admin", "salesOrder:reject"],
        closed: ["admin", "salesOrder:closed"],
        invalid: ["admin", "salesOrder:invalid"],
        stop: ["admin", "salesOrder:stop"],
        recover: ["admin", "salesOrder:recover"],
        history: ["admin", "salesOrder:history"],
        accept: ["admin", "salesOrder:accept"],
        lockStock: ["admin", "salesOrder:lockStock"],
        superPass: ["admin", "salesOrder:superPass"],
        ignorePromotionPass: ["admin", "salesOrder:ignorePromotionPass"],
        saveAndPass: ["admin", "salesOrder:saveAndPass"],
        priceInfo: ["admin", "salesOrder:priceInfo"],
        salesHistory: ["admin", "salesOrder:salesHistory"],
        exportDetail: ["admin", "salesOrder:exportDetail"],
        print: ["admin", "salesOrder:print"],
        addDetail: ["admin", "salesOrder:addDetail"],
        batchAddDetail: ["admin", "salesOrder:batchAddDetail"],
        salesGiftList: ["admin", "salesOrder:salesGiftList"],
        split: ["admin", "salesOrder:split"],
        copyToReturn: ["admin", "salesOrder:copyToReturn"],
        emptyBox: ["admin", "salesOrder:emptyBox"],
        superCancel: ["admin", "salesOrder:superCancel"],
        superUnCancel: ["admin", "salesOrder:superUnCancel"],
        settlement: ["admin", "salesOrder:settlement"],
        onAccount: ["admin", "salesOrder:onAccount"],
        checkBomStock: ["admin", "salesOrder:checkBomStock"]
      },
      rules: {
        warehouseId: [
          { required: true, message: "退货仓库不能为空", trigger: "blur" }
        ]
      },
      red: [
        "acceptBoxCount",
        "goodsCount",
        "boxCount",
        "cancelAmount",
        "unCancelAmount",
        "taxAmount",
        "noTaxAmount",
        "tax",
        "discountAmount",
        "oldTaxAmount",
        "oldNoTaxAmount",
        "oldTax",
        "acceptTaxAmount",
        "acceptNoTaxAmount",
        "acceptTax"
      ],
      // red:['taxAmount','noTaxAmount','acceptTaxAmount','acceptNoTaxAmount','cancelAmount','unCancelAmount'],
      // red:['acceptBoxCount','goodsCount','boxCount','boxCount','taxAmount','noTaxAmount','discountAmount','acceptTaxAmount',
      //   'acceptNoTaxAmount','cancelAmount','unCancelAmount'],
      depts: [],
      typeList: [],
      areaList: [],
      selectIds: [],
      isCopyToReturn: false,
      current: null, //选中操作的内容
      headerQuery: {
        modelName: "salesOrderDetail",
        url: "api/salesOrder/detail",
        userId: this.$store.state.user.user.userId
      },
      activeName: "1",
      detailParams: {
        id: 0
      },
      user: {},
      orderStatus: [],
      tableHeight: 0,
      showAccounting: false,
      deptUserIds: ""
    };
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  activated() {
    if (this.$route.query.isSave) {
      for (let key in this.query) {
        this.query[key] = null;
      }
      this.orderStatus = ["SAVE"];
      this.query.type = "1";
      this.query.isPrint = "0";
      // this.crud.toQuery()
    }
  },
  created() {
    this.setTableHeight();
    this.userId = this.$store.state.user.user.userId;
    this.is103 = window.location.href.includes("bw103");
    if (this.is103) {
      //获取角色
      this.user = this.$store.state.user.user;
      if (this.user.postName === "业务经理") {
        deptJuniorUserList({
          containsSelf: 1,
          businessAttr: 3,
          deptId: this.user.deptId
        }).then(res => {
          this.deptUserIds = res.content.map(item => item.id).join(",");
          this.crud.refresh();
        });
      } else {
        this.crud.refresh();
      }
    } else {
      this.crud.refresh();
    }
    this.orderStatus = ["SAVE"];
    if (this.$route.query.isSave) {
      this.query.type = "1";
      this.query.isPrint = "0";
    }
    this.getDepts();
    this.getTypeList();
    this.getAreaList();
    const isExceed = !!window.location.href.match(/isExceed/);
    this.isExceed = isExceed;
    this.crud.query.isExceed = isExceed ? 1 : null;
    this.crud.toQuery();
    this.$set(this.crud.props, "searchToggle", true);
  },

  mounted() {
    let _this = this;
    window.onresize = () => {
      return (() => {
        _this.setTableHeight();
      })();
    };
  },
  watch: {
    orderStatus(n) {
      this.query.orderStatus = n.join(",");
    },
    $route(now, old) {
      // now: 变化之后的数据
      // old: 变化之前的数据
      const isExceed = !!window.location.href.match(
        /\/sale\/salesOrder\?isExceed=1/
      );
      if (this.isExceed !== isExceed) {
        this.isExceed = isExceed;
        this.crud.query.isExceed = isExceed ? 1 : null;
        this.$set(this.crud.props, "searchToggle", true);
        this.crud.toQuery();
      }
    }
  },
  methods: {
    // toAccept(){
    //   console.log('EEEEEEEEEEEE')
    //   console.log(this.crud.selections)
    //   const exchangeWarehouseId = []
    //   // 获取选中的内容
    //   this.crud.selections.forEach(o => {
    //     o.
    //   })
    //   this.crud.saleToAccept()
    //   // if (this.crud.order.saleType===5&&this.crud.order.type===1) {
    //   //   this.dialogChangeWarehouse = true
    //   // }else {
    //   //   this.crud.toAccept(id)
    //   // }
    // },
    saveCancel() {
      this.$refs["cancelForm"].validate(valid => {
        if (valid) {
          const that = this;
          superCancel({ ...this.cancel, id: this.order.id }).then(res => {
            if (res.status === 200) {
              for (let key in that.cancel) {
                that.cancel[key] = null;
              }
              that.$message.success(res.msg);
              that.crud.refresh();
              that.superCancelShow = false;
            } else {
              that.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    toQuery() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle;
      this.crud.toQuery();
    },
    [CRUD.HOOK.beforeRefresh]() {
      if (this.is103) {
        if (this.user.postName === "业务代表") {
          //业务代表只能看到自己的
          this.crud.query.createUserId = this.user.userId;
        } else if (this.user.postName === "业务经理") {
          //业务经理只能看到自己部门的
          this.crud.query.createUserIds = this.deptUserIds;
        }
      }
      return true;
    },
    saveAccounting() {
      saveAccounting({
        customerId: this.customerAccounting,
        orderIds: this.crud.selections[0].id
      }).then(res => {
        if (res.status === 200) {
          this.$message.success("挂账成功");
          this.showAccounting = false;
          this.crud.refresh();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    setQuery(id) {
      const idDate = Date.now().toString();
      getSalesOrderPreviousNextPageIdList({
        ...this.query,
        id,
        ...this.crud.page,
        sort: this.query.sort || this.crud.sort
      }).then(res => {
        sessionStorage.setItem(idDate, JSON.stringify(res.data));
      });
      this.$router.push({
        path: `salesorderDetail/${id}?idDate=${idDate}&isExceed=${
          this.isExceed
        }`
      });
    },
    toDetail(url, row) {
      sessionStorage.setItem("salesOrderDetailId", "-1");
      this.crud.toDetail(url, row);
    },
    setDeductionAmount(e) {
      const num = Number(e);
      if (num < 0 || num > this.settlementData.customerDeductionAmount) {
        this.settlementForm.deductionAmount = 0;
      }
      this.deductionAmount();
    },
    deductionAmount() {
      this.settlementForm.curCancelAmount = (
        Number(this.settlementData.order.unCancelAmount) +
        Number(this.settlementForm.tailAmount || 0) -
        Number(this.settlementForm.deductionAmount || 0)
      ).toFixed(6);
    },
    setTableHeight() {
      const ratio = this.getRatio() / 100;
      this.tableHeight = (window.screen.height - 200 * ratio) / ratio;
    },
    saveSettlement() {
      if (this.settlementForm.receiptIds) {
        this.settlementForm.id = this.settlementData.order.id;
        settlementSave(this.settlementForm);
        this.settlementShow = false;
      } else {
        this.$message.error("请先选择收款单");
      }
    },
    getNoStr(val, type, prop) {
      let str = "";
      val.forEach(item => {
        const itemNode = this.getTreeName(this[type], item);
        str = this.getNode(itemNode, str);
      });
      this.query[prop] = str;
    },
    unCancel(id) {
      const that = this;
      superUnCancel({ id: id }).then(res => {
        if (res.status === 200) {
          that.$message.success(res.msg);
          that.crud.refresh();
        } else {
          that.$message.error(res.msg);
        }
      });
    },
    toUnAccept(event) {
      this.crud.acceptLoading = true;
      const ids = [];
      if (event) {
        const href = location.href.split("/");
        if (href[5].includes("copyId")) {
          const strs = event.split("=");
          ids.push(strs[1]);
        } else {
          ids.push(event);
        }
      } else {
        const _datas = this.crud.selections;
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id);
        });
      }
      this.crud.crudMethod
        .unAccept({ ids, isCleanReceiveDate: 1 })
        .then(() => {
          this.crud.acceptLoading = false;
          this.crud.resetForm();
          this.$message.success("取消验收成功");
          this.crud.refresh();
        })
        .catch(() => {
          this.crud.acceptLoading = false;
          this.$message.error("取消验收失败，稍后再试");
        });
    },
    getTreeName(treeList, id) {
      let _this = this;
      for (let i = 0; i < treeList.length; i++) {
        let treeItem = treeList[i];
        if (treeItem.id === id) {
          return treeItem;
        } else {
          if (treeItem.children && treeItem.children.length > 0) {
            let res = _this.getTreeName(treeItem.children, id);
            if (res) {
              return res;
            }
          }
        }
      }
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    getRatio() {
      var ratio = 0;
      var screen = window.screen;
      var ua = navigator.userAgent.toLowerCase();

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else if (~ua.indexOf("msie")) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
      } else if (
        window.outerWidth !== undefined &&
        window.innerWidth !== undefined
      ) {
        ratio = window.outerWidth / window.innerWidth;
      }

      if (ratio) {
        ratio = Math.round(ratio * 100);
      }
      return ratio;
    },
    async printIsSave() {
      if (
        this.dict.t_sales_order_save_order_status_is_allow_print[0].value == "0"
      ) {
        if (this.crud.selections.some(item => item.orderStatus === "SAVE"))
          return this.$message.error("保存状态单据不允许打印");
      }

      if (this.crud.selections.every(item => item.isPrint == "1")) {
        this.$confirm("销售单已打印，请确认是否重复打印", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.crud.preView();
          setTimeout(() => {
            this.crud.refresh();
          }, 6000);
        });
        return;
      }
      this.crud.preView();
      setTimeout(() => {
        this.crud.refresh();
      }, 6000);
    },
    async feiEPrint() {
      this.$confirm("确认是否打印小票", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const ids = [];
        this.crud.selections.forEach(o => {
          ids.push(o.id);
        });
        this.feiEPrintHandler(ids);
        setTimeout(() => {
          this.crud.refresh();
        }, 6000);
      });
    },
    /**
     * 飞鹅打印
     */
    feiEPrintHandler(ids) {
      if (ids.length === 0) {
        return this.$message.error("请先勾选需要打印的销售订单");
      }
      feiEPrint({ ids: ids, templateId: "" }).then(res => {
        if (res.status === 200) {
          that.$message.success(res.msg);
          that.crud.refresh();
        } else {
          that.$message.error(res.msg);
        }
      });
    },
    //线上支付查询
    async onlinePayQuery() {
      const ids = this.crud.selections.map(item => item.id).join(",");
      onlinePayQuery({ orderIds: ids }).then(res => {
        if (res.status === 200) {
          that.$message.success(res.msg);
          that.crud.refresh();
        } else {
          that.$message.error(res.msg);
        }
      });
      setTimeout(() => {
        this.crud.refresh();
      }, 6000);
    },
    handleClose() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle;
    },
    bomStockCheck() {
      checkBomStock(this.crud.selections[0].id).then(res => {
        if (res.status === 200) {
          this.$message.success("更新成功");
        }
      });
    },
    cancelCUDis() {
      this.isVolume = false;
      this.goodsBrandDiscountList = null;
      this.goodsDiscountList = null;
      this.goodsTypeDiscountList = null;
    },
    handleDisCl() {
      let criteria = {
        orderId: this.crud.selections[0].id,
        type: this.activeName,
        goodsBrandDiscountList: this.goodsBrandDiscountList,
        goodsDiscountList: this.goodsDiscountList,
        goodsTypeDiscountList: this.goodsTypeDiscountList
      };
      batchDiscount(criteria).then(res => {
        // this.areaList = res
        this.isVolume = false;
        this.$message({
          message: "修改成功",
          type: "success"
        });
      });
    },
    acceptInfo() {
      crudSalesOrder.salesOrdersyncSalesOrderAcceptInfo().then(res => {
        if (res.status === 200) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleClick(e) {
      let criteria = {
        orderId: this.crud.selections[0].id,
        type: this.activeName
      };
      getBatchDiscountInfo(criteria).then(res => {
        this.goodsBrandDiscountList = res.data.goodsBrandDiscountList;
        this.goodsDiscountList = res.data.goodsDiscountList;
        this.goodsTypeDiscountList = res.data.goodsTypeDiscountList;
        // this.areaList = res
      });
    },
    volume() {
      if (this.crud.selections[0].orderStatus != "SAVE") {
        this.$message({
          message: "保存状态下才能操作",
          type: "error"
        });
        return;
      }
      let criteria = {
        orderId: this.crud.selections[0].id,
        type: this.activeName
      };
      this.isVolume = true;
      getBatchDiscountInfo(criteria).then(res => {
        this.goodsBrandDiscountList = res.data.goodsBrandDiscountList;
        this.goodsDiscountList = res.data.goodsDiscountList;
        this.goodsTypeDiscountList = res.data.goodsTypeDiscountList;
        console.log("crudSalesOrder", res);
        // this.areaList = res
      });
    },
    changeDetailQuery(row) {
      this.detailParams.id = row.id;
      this.crud.selectRow(row);
    },
    getValue(e) {
      if (this.dataExtent) {
        this.query.startTime = this.dataExtent[0];
        this.query.endTime = this.dataExtent[1];
      } else {
        this.query.startTime = null;
        this.query.endTime = null;
      }
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false;
      //去重，已经去重
      // let arr = this.detailList.map(detail=>detail.goodsId)
      // let _goods = []
      // let result = []
      // goods.forEach(good => {
      //   if(!arr.includes(goods.goodsId)){
      //       this.detailList.push(goods)
      //   }
      // })
      this.detailList = goods;
      // this.calcuForm()
    },
    showHistory(row) {
      this.showHistoryDialog = true;
      this.current = row;
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.afterRefresh]() {
      const returnGoodsList = this.crud.data.filter(item => item.type === 2);
      for (let i of returnGoodsList) {
        for (let key of this.red) {
          i[key] = i[key] * -1;
        }
      }
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    [CRUD.HOOK.afterEditError](crud, form) {
      this.cancelCU();
    },
    [CRUD.HOOK.afterSubmit](crud, form) {
      this.cancelCU();
    },
    handleCopyToReturn() {
      this.isCopyToReturn = true;
    },
    settlement() {
      settlementDraw({ customerId: this.crud.selections[0].customerId }).then(
        res => {
          if (res.status === 200) {
            this.settlementData.customerDeductionAmount =
              res.data.customerDeductionAmount;
            this.settlementData.customerId = this.crud.selections[0].customerId;
            this.settlementData.order = this.crud.selections[0];
            (this.settlementForm = {
              deductionAmount: 0,
              receiptIds: "",
              curCancelAmount: 0,
              tailAmount: 0
            }),
              (this.settlementShow = true);
          } else {
            this.$message.error(res.msg);
          }
        }
      );
    },
    //检查bom库存减少
    showLackBom() {
      this.selectIds = this.crud.selections.map(item => item.id);
      this.dialogCheckMaterialWareHouse = false;
      this.lackBomShow = true;
    },
    cancelCU() {
      this.form.id = null;
      this.form.warehouseId = null;
      this.isCopyToReturn = false;
    },
    getDepts() {
      getDepts({ status: 1 }).then(res => {
        this.depts = res;
      });
    },
    resetQuery() {
      this.dataExtent = [];
      this.orderStatus = ["SAVE"];
      this.crud.resetQuery();
    },
    getTypeList() {
      getCustomerTypeTree({ page: 0, size: 999 }).then(res => {
        this.typeList = res;
      });
    },
    getAreaList() {
      getAreaTree().then(res => {
        this.areaList = res;
      });
    },
    // updateData(){
    //   this.$forceUpdate()
    // },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    toEdit(row) {
      let id = 0;
      if (row) {
        id = row.id;
      }
      this.$router.push({
        path: "salesOrderDetail/" + id
      });
    },
    goRefund() {
      const row = this.crud.selections[0];
      if (row.payStatus != "2") {
        this.$message({
          message: "订单退款状态下才能操作",
          type: "error"
        });
        return;
      }

      const params = {
        orderId: row.id,
        outTradeNo: row.outTradeNo,
        payType: row.payType
      };
      refundOrder(params).then(res => {
        console.log("refundOrder", res);
        if (res.status === 200) {
          this.$message.success(res.msg);
          this.dialogRefund = false;
          this.crud.refresh();
        }
      });
    },
    /**
     *
     * 拒绝退款
     * */
    refuseRefund() {
      const row = this.crud.selections[0];
      if (row.payStatus != "2") {
        this.$message({
          message: "订单退款状态下才能操作",
          type: "error"
        });
        return;
      }
      if (!this.refuseRefundReason) {
        this.$message({
          message: "请输入拒绝退款原因",
          type: "error"
        });
        return;
      }
      const params = {
        orderId: row.id,
        outTradeNo: row.outTradeNo,
        payType: row.payType,
        refundRejectReason: this.refuseRefundReason
      };
      refundOrder(params).then(res => {
        console.log("refundOrder", res);
        if (res.status === 200) {
          this.$message.success(res.msg);
          this.dialogRefund = false;
          this.crud.refresh();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.red {
  color: red;
}
.blue {
  color: blue !important;
}
</style>
